/**
 * 作者: wgx
 * 日期: 2024-10-24 16:24:32
 * 备注: 用户建筑表
 */
package com.motu.monstercity.server.game.userdata;

import com.motu.monstercity.protocol.Common.PBUserBuild;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.build.BuildConstant;
import com.motu.monstercity.server.game.commondata.build.BuildMain;
import com.motu.monstercity.server.game.commondata.build.BuildUpgrade;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.secretary.SecretaryPotentialSkill;
import com.motu.monstercity.server.game.commondata.world.WorldRadar;
import com.motu.monstercity.server.game.log.MotuLogManager;
import com.motu.monstercity.server.game.logic.*;
import io.vertx.core.json.JsonArray;

import java.util.List;

public class UserBuild extends UserBuildModel {
    public UserBuild() {
        super();
    }

    public UserBuild(long userId, int buildId, long num, int isUnlock) {
        super();
        putUserId(userId);
        putBuildId(buildId);
        putNum(num);
        putLevel(1);// 初始都是等级1
        if (buildId == BuildConstant.BUILD_ID_CITY_CENTER) {// 后台设置测试账号等级时未解锁市政中级，保证等级一致
            UserInfo userInfo = GameUser.getUserInfo(userId);
            if (userInfo.getLevel() > 1) {
                putLevel(userInfo.getLevel());
            }
        }
        this.unlockPartnerSeat();
        putIsUnlock(isUnlock);
    }

    // 放置建筑,涉及到模块解锁,摆放商业建筑会提升城市收益，摆放雷达会增加干员战力
    public void putIsPlace(PBUserData.Builder pbUserData, UserInfo userInfo, UserPower userPower) {
        super.putIsPlace(1);
        if (isBusinessBuild()) {// 商业建筑要重算城市收益
            userPower.addBuildId(getBuildId());// 增加一个建筑id
            long totalEarn = countTotalEarn(userPower);// 总收益
            userPower.addBuildEarn(pbUserData, userInfo, totalEarn);

            int totalLevel = BuildManager.countBusinessBuildLevel(userId);// 商业建筑的总等级
            MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_43, totalLevel);// 领取完奖励会重置进度 更新主线任务,成就,日常任务的进度
            MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_129, totalLevel);// 更新主线任务,成就,日常任务的进度
            RankActManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_43, totalLevel);
            MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_129, totalLevel);
        }
        if (isRadarBuild()) {// 摆放雷达 会提升玩家战力。增加城市收益
            userPower.updatePowerAddWorldCv(pbUserData, userInfo, this);
        }
    }


    // 是否已经解锁
    public boolean isUnlock() {
        return getIsUnlock() == 1;
    }

    public boolean isPlace() {
        return getIsPlace() == 1;
    }

    public PBUserBuild.Builder takeInitBuilder() {
        PBUserBuild.Builder sb = super.takeInitBuilder();
        addDetailData(sb);// 设置详情信息
        return sb;
    }

    public PBUserBuild.Builder takeBuilder() {
        PBUserBuild.Builder sb = super.takeBuilder();
        addDetailData(sb);// 设置详情信息
        return sb;
    }

    public void addDetailData(PBUserBuild.Builder sb) {
        sb.putDetail(BuildConstant.DETAIL_KEY_BASE_CN, takeBaseEarnRecruit() + "");// 经营收益，招募收益，客户端需要加上战力收益
        sb.putDetail(BuildConstant.DETAIL_KEY_LEVEL_PER, takeBuildEarnAdd() + "");// 建筑升级的加成
        sb.putDetail(BuildConstant.DETAIL_KEY_PARTNER_PER, getPartnerAdd2() + "");// 委派干员的加成
    }

    // 解锁委派槽位
    public void unlockPartnerSeat() {
        int max = AllParam.BUILD_DETAIL_LIMIT.length;
        for (int i=max;i>0;i--) {
            int value = AllParam.BUILD_DETAIL_LIMIT[i-1];
            if (getRecruitNum() >= value && getSeatNum() < i) {
                putSeatNum(i);
                break;
            }
        }
    }

    //  去掉委派的干员Id
    public long removePartnerId(PBUserData.Builder pbUserData, UserInfo userInfo, UserPower userPower, int partnerId) {
        JsonArray result = new JsonArray();
        JsonArray list = getPartnerArray();
        for (int i=0;i<list.size();i++) {
            int pp = list.getInteger(i);
            if (pp != partnerId) {
                result.add(pp);
            }
        }
        return updatePartnerAdd(pbUserData, userInfo, userPower, result.toString());
    }

    // 增加数量,并记录消耗获得日志 装饰类建筑
    public void addNum(UserInfo userInfo, int num, Object... params) {
        long balance = getNum();// 当前余额
        long dbid = 0;
        MotuLogManager.logItemIncome(userInfo, getBuildId(), dbid, balance, num, params);
        super.addNum(num);
    }

    // 扣除数量并记录消耗获得日志 主要装饰类建筑
    public void subNum(UserInfo userInfo, long num, Object... params) {
        long balance = getNum();// 当前余额
        if (num > balance) {
            return;// 余额不足
        }
        long dbid = 0;
        MotuLogManager.logItemConsume(userInfo, getBuildId(), dbid, balance, num, params);
        super.addNum(-num);
    }

    public long addRecruitNum(UserInfo userInfo, UserPower userPower, int addValue) {
        super.addRecruitNum(addValue);
        return reCountEarn(userInfo, userPower);
    }

    // 派遣的干员有变化时,会影响城市收益,需要重算
    public long updatePartnerAdd(PBUserData.Builder pbUserData, UserInfo userInfo, UserPower userPower, String partner) {
        if (!this.partner.equals(partner)) {
            super.putPartner(partner);
            putPartnerAdd2(takePartnerEarnAdd());
            return reCountEarn(userInfo, userPower);
        } else {
            return 0L;
        }
    }


    //  统计所有委派干员的技能加成
    public int takePartnerEarnAdd() {
        JsonArray partnerIdList = getPartnerArray();// 派遣的干员列表
        int addValue = 0;
        long userId = getUserId();
        for (int i=0; i<partnerIdList.size(); i++) {
            int partnerId = partnerIdList.getInteger(i);
            UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
            addValue += userPartner.countSkillAddEarn();
        }
        return addValue;// 返回2200,表示总的加成22%
    }

    // 重算建筑的赚速 返回增加的值, 适合多个建筑有赚速更新,最后再一起更新总赚速
    public long reCountEarn(UserInfo userInfo, UserPower userPower) {
        BuildMain buildMain = BuildManager.getBuildMain(getBuildId());
        if (!buildMain.isBusinessBuild()) {
            return 0L;// 非商业建筑不做赚速重算
        }
        long newEarn = countTotalEarn(userPower);
        //System.out.println("newearn:" + newEarn + " oldearn:" + getTotalEarn());
        long addEarn = newEarn - getTotalEarn();// 增加的值
        if (newEarn != getTotalEarn()) {// 新算出来的城市收益 不等于 旧的城市收益
            super.putTotalEarn(newEarn);
        }
        return addEarn;// 增加的值
    }

    /**
     * 计算总的赚速,固定值*百分比  建筑升级有加成,同性格的秘书有加成,委派的干员技能有加成 银行建筑有加成,装饰类建筑加成
     * @param userPower
     * @return
     */
    public long countTotalEarn(UserPower userPower) {
        double pp = userPower.getPower();
        double baseValue = takeBaseEarnRecruit() + pp / 1000;// 基础收益=经营收益（build_main表的recruit_add字段）*(伙计数量 + 1) + 战力收益 总战力/1000
        // 总的加成百分比
        int characterType = getCharacterType();// 性格类型
        int levelUpAdd = takeBuildEarnAdd();// 建筑升级加成
        int secrAdd = SkillManager.countAddByCharacterType(characterType, userPower.getEarnAddSecrPerArray());// 秘书经营技能加成
        int partnerAdd = getPartnerAdd2();// 委派干员的技能加成
        int bankAdd = userPower.getEarnAddBankPer();// 金库的加成
        int decorateAdd = SkillManager.countAddByCharacterType(characterType, userPower.getEarnAddDecoratePerArray());// 装饰类建筑地标类建筑的加成
        int caveAdd = userPower.getEarnAddCavePer();// 地下洞窟的加成
        int foodAdd = SkillManager.countAddByCharacterType(characterType, userPower.getEarnAddFoodPerArray());// 美食攻略的加成
        int unionAdd = SkillManager.countAddByCharacterType(characterType, userPower.getEarnAddUnionPerArray());// 联盟建筑的加成

        //System.out.println("baseValue:" + baseValue + " levelUpAdd:" + levelUpAdd + " secradd:" + secrAdd + " partnerAdd:" + partnerAdd + " bankAdd:" + bankAdd + " decorateAdd:" + decorateAdd + " caveadd:" + caveAdd + " foodadd:" + foodAdd + " union:" + unionAdd);
        int totalAdd = levelUpAdd + secrAdd + partnerAdd + bankAdd + decorateAdd + caveAdd + foodAdd + unionAdd;
        double total = baseValue + baseValue * totalAdd / 10000;
        return (long) Math.floor(total);
    }


    // 经营收益，招募收益，伙计赚速
    public long takeBaseEarnRecruit() {
        int buildId = getBuildId();
        BuildMain buildMain = BuildManager.getBuildMain(buildId);
        if (buildMain == null) {
            return 0;
        }
        int baseValue = buildMain.getRecruitAdd();//单个伙计的赚速
        return baseValue * (getRecruitNum() + 1);
    }

    // 获取建筑的 升级加成=build_upgrade表的earn_speed_addition字段
    public int takeBuildEarnAdd() {
        int buildId = getBuildId();
        BuildUpgrade buildUpgrade = BuildManager.getBuildUpgrade(buildId, getLevel());
        if (buildUpgrade == null) {
            return 0;
        }
        return buildUpgrade.getPowerAdd();// 配置20000
    }

    // 是否商业建筑
    public boolean isBusinessBuild() {
        BuildMain buildMain = BuildManager.getBuildMain(getBuildId());
        return buildMain.isBusinessBuild();
    }

    // 是否雷达，放置雷达会提升玩家战力，提升城市收益
    public boolean isRadarBuild() {
        BuildMain buildMain = BuildManager.getBuildMain(getBuildId());
        return buildMain.isBuildRadar();
    }

    // 雷达的战力加成
    public int takeRadarAdd() {
        if (!isRadarBuild()) {
            return 0;
        }
        WorldRadar worldRadar = WorldManager.getWorldRadar(getLevel());
        if (worldRadar == null) {
            return 0;
        } else {
            return worldRadar.getPowerAdd();
        }
    }

    // 该建筑的性格类型
    public int getCharacterType() {
        BuildMain buildMain = BuildManager.getBuildMain(getBuildId());
        if (buildMain == null) {
            return 0;
        } else {
            return buildMain.getCharacterType();
        }
    }
}
